package com.linewell.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.linewell.system.dao.ISysDepartmentDao;
import com.linewell.system.model.SysDepartment;
import com.linewell.system.pagemodel.DataGrid;
import com.linewell.system.pagemodel.DepartmentTreeNode;
import com.linewell.system.pagemodel.PageHelper;
import com.linewell.system.service.ISysDepartmentService;
import com.linewell.system.utils.DepartmentTreeUtil;
import com.linewell.system.utils.HqlHelper;

/**
 * 实现SysDepartment接口方法 
 */
@Service
public class SysDepartmentServiceImpl implements ISysDepartmentService {

	@Autowired
	private ISysDepartmentDao sysDepartmentDao;

	@Override
	public DataGrid datagrid(SysDepartment c, PageHelper ph,Integer depId) {
		// TODO Auto-generated method stub
		DataGrid dg = new DataGrid();
		List<SysDepartment> cml = new ArrayList<SysDepartment>();
		// 用来放置查询的条件
		Map<String, Object> params = new HashMap<String, Object>();

		// 注意下面为HQL语句，里面sql的关键字大小写不敏感，其它是敏感的,from后面是model类名称
		StringBuffer hql = new StringBuffer("from SysDepartment t where 1=1 ");

		// 以下为查询条件
		
		if(depId != null && !"".equals(depId)){
			hql.append("  AND FIND_IN_SET(t.depId,getChildDepId("+depId+")) > 0 ");
		}
		
		
		hql = HqlHelper.orderHql(hql, ph); // 排序
		List<SysDepartment> lstAll = sysDepartmentDao.find(hql.toString(), params, ph.getPage(), ph.getRows());
		List<DepartmentTreeNode> lstTree = null;
		if (lstAll != null && lstAll.isEmpty() == false) {
			DepartmentTreeUtil treeUtil = new DepartmentTreeUtil();
			treeUtil.setLstAll(lstAll);
			lstTree = treeUtil.findById(null);
		}
		dg.setRows(lstTree);
		dg.setTotal(sysDepartmentDao.count("select count(*) " + hql, params));
		return dg;
	}

	@Override
	public List<SysDepartment> getAllDepaetment(Integer type,Integer depId) {
		return sysDepartmentDao.getAllDepaetment(type,depId);
	}

	@Override
	public boolean save(SysDepartment sysDepartment) {
		sysDepartmentDao.save(sysDepartment);
		return true;
	}

	@Override
	public List<SysDepartment> get(String id) {
		String hql = "from SysDepartment s where s.depId=" + id;
		return sysDepartmentDao.find(hql);
	}

	@Override
	public boolean update(SysDepartment c) {

		return sysDepartmentDao.updateAll(c);
	}

	@Override
	public boolean removeAll(Integer id) {
		// TODO Auto-generated method stub
		return sysDepartmentDao.remove(id);
	}

	@Override
	public boolean deleteAll(Integer id) {
		// TODO Auto-generated method stub
		return sysDepartmentDao.deleteAll(id);
	}

	@Override
	public boolean saveOrUpdate(SysDepartment sysDepartment) {
		sysDepartmentDao.saveOrUpdate(sysDepartment);
		return true;
	}

}
